package org.vnl.platform.dk.util;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Locale;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

/**
 * I18n時使用，可以直接取出本地化的文字
 * @author Vaughan
 *
 */
public class I18nUtils {

    private static final Logger logger = Logger.getLogger(I18nUtils.class);
    
    private static I18nUtils instance;
    
    private HashMap<String, HashMap<Locale, ResourceBundle>> bundlesPool;
    
    private I18nUtils() {
        
    }
    
    public static I18nUtils getInstance() { 
        if (instance == null) {
            instance = new I18nUtils();
        }
        return instance;
    }
    
    /**
     * 
     * @param key 
     * @param params
     * @param baseName
     * @param locale
     * @return
     */
    public String getFromatedString(String key, Object[] params, String baseName, Locale locale) {
        String str = getString(key, baseName, locale);
        if (str.equals(key)) {
            return str;
        }
        return MessageFormat.format(str, params);
    }
    
    public String getString(String key, String baseName, Locale locale) {
        ResourceBundle bundle = null;
        
        // 確保locale不會為NULL
        Locale l = locale == null ? Locale.getDefault() : locale;
        
        HashMap<Locale, ResourceBundle> map = bundlesPool.get(baseName);
        if (map == null) {
            bundle = init(baseName, l);
        } else {
            bundle = map.get(l);
            if (bundle == null) {
                bundle = init(baseName, l);
            }
        }
        if (bundle == null) {
            return key;
        } else {
            String result = bundle.getString(key);
            return result;
        }
    }
    
    private ResourceBundle init(String baseName, Locale locale) {
        Locale l = locale == null ? Locale.getDefault() : locale;
        ResourceBundle bundle = null;
        try {
            bundle = ResourceBundle.getBundle(baseName, l);
        } catch (Exception e) {
            try {
                bundle = ResourceBundle.getBundle(baseName,l,Thread.currentThread().getContextClassLoader());
            } catch (Exception ee) {
                logger.error("Load Resource Bundle Error("+baseName+")", ee);
                return null;
            }
        }
        HashMap<Locale, ResourceBundle> map = bundlesPool.get(baseName);
        if (map == null) {
            map = new HashMap<Locale, ResourceBundle>();
            bundlesPool.put(baseName, map);
        }
        map.put(l, bundle);
        return bundle;
    }
}
